﻿using DzInfo.Tools;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace DzInfo.SerivesPlugin.GXD
{
    [Description("国信达:采购订单手工关闭时，自动结案上游委外订单"), HotUpdate]
    public class ToCloseSer : AbstractOperationServicePlugIn
    {
        public override void EndOperationTransaction(EndOperationTransactionArgs e)
        {
            base.EndOperationTransaction(e);
            string formId = this.BusinessInfo.GetForm().Id;
            foreach (var obj in e.DataEntitys)
            {
                if (formId.EqualsIgnoreCase(KdFomId.PUR_PurchaseOrder.ToString()))
                {
                    List<string> errList = new List<string>();

                    string opNumber = this.FormOperation.Operation;
                    int fid = Convert.ToInt32(obj["Id"]);
                    string wwBillNo = GetWwBillNo(fid);
                    if (opNumber.EqualsIgnoreCase(KDOperationNumber.BillClose.ToString()))
                    {
                        if (!wwBillNo.IsNullOrEmptyOrWhiteSpace())
                        {
                            string data = KDApi.ExecuteParameter(wwBillNo, "", null);
                            var res = KDApi.Execute(this.Context, KdFomId.SUB_SUBREQORDER.ToString(), "ToClose", data);
                            var _res = JsonConvert.SerializeObject(res);
                            IOperationResult result = GetResult(_res, wwBillNo);
                            this.OperationResult.MergeResult(result);
                        }
                    }
                    if (opNumber.EqualsIgnoreCase(KDOperationNumber.BillUnClose.ToString()))
                    {
                        if (!wwBillNo.IsNullOrEmptyOrWhiteSpace())
                        {
                            string data = KDApi.ExecuteParameter(wwBillNo, "", null);
                            var res = KDApi.Execute(this.Context, KdFomId.SUB_SUBREQORDER.ToString(), "UndoToRelease", data);
                            var _res = JsonConvert.SerializeObject(res);
                            IOperationResult result = GetResult(_res, wwBillNo);
                            this.OperationResult.MergeResult(result);
                        }
                    }
                    //业务关闭 行关闭
                    if (opNumber.EqualsIgnoreCase(KDOperationNumber.MRPClose.ToString()))
                    {
                        string msg = "";
                        var curRows = this.Option.GetBillOperationSelectedRows();
                        List<object> pkes = new List<object>();
                        foreach (var curRow in curRows)
                        {
                            object pkEntryIds = Getwweid(curRow.EntryPrimaryKeyValue);
                            pkes.Add(pkEntryIds);
                        }
                        var data2 = new
                        {
                            PkEntryIds = pkes.ToArray()
                        };
                        string data = JsonConvert.SerializeObject(data2);
                        var res = KDApi.Execute(this.Context, KdFomId.SUB_SUBREQORDER.ToString(), "ToClose", data);
                        if (res.Result.ResponseStatus.IsSuccess)
                        {
                            msg = JsonConvert.SerializeObject(res);
                        }
                        else
                        {
                            if (res.Result.ResponseStatus.Errors.Count > 0)
                            {
                                foreach (var mes in res.Result.ResponseStatus.Errors)
                                {
                                    errList.Add(mes.Message);
                                }
                            }
                            msg = string.Join(",", errList);
                        }
                        IOperationResult operationResult = GetZInfosOK(msg, res.Result.ResponseStatus.IsSuccess);
                        this.OperationResult.MergeResult(operationResult);
                    }
                }
            }
        }

        private object Getwweid(string entryPrimaryKeyValue)
        {
            string sql = string.Format(@"/*dialect*/ 
            SELECT T4.FID,T3.FENTRYID
            FROM T_PUR_POORDER T0
                 JOIN T_PUR_POORDERENTRY T1 ON T1.FID = T0.FID
                 JOIN T_PUR_POORDERENTRY_LK T2 ON T2.FENTRYID = T1.FENTRYID
                 JOIN T_SUB_REQORDERENTRY T3 ON T3.FID = T2.FSBILLID
                                                AND T3.FENTRYID = T2.FSID
                 JOIN T_SUB_REQORDER T4 ON T4.FID = T3.FID
            WHERE T1.FENTRYID={0} ", entryPrimaryKeyValue);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            if (doc.Count > 0)
            {
                var par = new
                {
                    Id = doc[0][0].ToString(),
                    EntryIds = doc[0][1].ToString()
                };
                return par;
            }
            return null;
        }

        private IOperationResult GetZInfosOK(string msg, bool isSuccess)
        {
            string info = "";
            if (isSuccess)
            {
                info = "委外订单自动结案成功：" + msg;
            }
            else
            {
                info = "委外订单自动结案不成功,原因：" + msg;
            }
            IOperationResult operationResult = new OperationResult();
            operationResult.OperateResult = new OperateResultCollection()
            {
                new OperateResult()
                {
                    SuccessStatus = isSuccess,
                    Message = info,
                    MessageType =isSuccess==true? MessageType.Normal:MessageType.FatalError,
                    Name = "自动结案委外订单",
                    PKValue = 0
                }
            };
            return operationResult;
        }

        private IOperationResult GetResult(string res, string wwBillNo)
        {
            IOperationResult operationResult = new OperationResult();
            operationResult.OperateResult = new OperateResultCollection()
            {
                new OperateResult()
                {
                    SuccessStatus = true,
                    Message = "自动结案："+wwBillNo+"_"+res,
                    MessageType = MessageType.Normal,
                    Name = "自动结案",
                    PKValue = 0
                }
            };
            return operationResult;
        }

        private string GetWwBillNo(int fid)
        {
            string sql = string.Format(@"/*dialect*/ 
            SELECT T4.FBILLNO
            FROM T_PUR_POORDER T0
                 JOIN T_PUR_POORDERENTRY T1 ON T1.FID = T0.FID
                 JOIN T_PUR_POORDERENTRY_LK T2 ON T2.FENTRYID = T1.FENTRYID
                 JOIN T_SUB_REQORDERENTRY T3 ON T3.FID = T2.FSBILLID
                                                AND T3.FENTRYID = T2.FSID
                 JOIN T_SUB_REQORDER T4 ON T4.FID = T3.FID
            WHERE T0.FID = {0} ", fid);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            if (doc != null && doc.Count > 0)
            {
                return doc[0][0].ToString();
            }
            return "";
        }
    }
}
